package xyz.ibenben.zhongdian.system.controller.sys;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.*;

import xyz.ibenben.zhongdian.common.annotation.SystemControllerLog;
import xyz.ibenben.zhongdian.common.constants.Constants;
import xyz.ibenben.zhongdian.common.util.FileUtil;
import xyz.ibenben.zhongdian.system.controller.BaseController;
import xyz.ibenben.zhongdian.system.entity.sys.*;
import xyz.ibenben.zhongdian.system.form.sys.SysUserForm;
import xyz.ibenben.zhongdian.system.service.impl.RedisService;
import xyz.ibenben.zhongdian.system.service.sys.*;

/**
 * 系统用户控制类
 * 提供了一些基本的服务，如初始化、获取用户列表等方法。
 * spring mvc思想 通过controller来调用service里的方法，
 * service里的方法再通过调用Dao来实现对数据的操作
 * 返回值统统是String类型的返回页面有统一的安排方便代码提取
 *
 * @author chenjian
 * @since 2017年9月27日上午10:57:28
 */
@Controller
@SessionAttributes("sysUserForm")
@RequestMapping("/sys/sysUser")
public class SysUserController extends BaseController{
	/* 实体名称 */
	private static final String ENTITYNAME = "sysUser";

	private final SysUserService userService;
	private final SysUserRoleService userRoleService;
	private final SysRoleService roleService;
	private final RedisService redisService;

	@Autowired
	public SysUserController(SysUserService userService, SysUserRoleService userRoleService, SysRoleService roleService, RedisService redisService) {
		this.userService = userService;
		this.userRoleService = userRoleService;
		this.roleService = roleService;
		this.redisService = redisService;
	}

	/**
	 * 初始化
	 * @param map 参数
	 * @param sysUserForm 条件参数
	 */
	@ModelAttribute
	public void init(Model map, @ModelAttribute SysUserForm sysUserForm){
		map.addAttribute("provinceList", redisService.get("provinceList"));
		map.addAttribute("cityList", redisService.get("cityList"));
		map.addAttribute("regionList", redisService.get("regionList"));
		SysUserForm newSysUserForm = new SysUserForm();
		if(sysUserForm != null){
			newSysUserForm = sysUserForm;
		}
		map.addAttribute(String.format(Constants.FORMNAME, ENTITYNAME), newSysUserForm);
	}

	/**
	 * 获取用户列表
	 * @param map 参数
	 * @param sysUserForm 条件参数
	 * @return 页面
	 */
	@RequestMapping(value="/getall")
	@SystemControllerLog(description = "获取用户列表")
	public String getall(Model map, @ModelAttribute SysUserForm sysUserForm){
		map.addAttribute(String.format(Constants.FORMNAME, ENTITYNAME), sysUserForm);
		Page<SysUser> page = PageHelper.startPage(sysUserForm.getPageIndex(), sysUserForm.getPageSize());
		List<SysUser> list = userService.selectByExample(sysUserForm.buildSearchCommond());
		if(list != null && !list.isEmpty()){
			for(SysUser user: list){
				if(null != user.getProvince()){
					user.setProvinceName(redisService.get(user.getProvince().toString()).toString());
				}
				if(null != user.getCity()){
					user.setCityName(redisService.get(user.getCity().toString()).toString());
				}
				if(null != user.getRegion()){
					user.setRegionName(redisService.get(user.getRegion().toString()).toString());
				}
			}
		}
		map.addAttribute(String.format(Constants.LISTENTITY, ENTITYNAME), list);
		map.addAttribute(Constants.PI, page.toPageInfo());
		return "sys/" + String.format(Constants.LISTPAGE, ENTITYNAME);
	}

	/**
	 * 删除用户记录
	 * @param id 主键
	 * @param request 请求
	 * @return 页面
	 */
	@RequestMapping(value = "/delete")
	@SystemControllerLog(description = "删除用户记录")
	public String delete(@RequestParam("id") Long id, HttpServletRequest request) {
		userService.delete(id, request);
		return String.format(Constants.REDIRECT, "sys/" + ENTITYNAME);
	}

	/**
	 * 删除用户列表
	 * @param sysUserForm 条件参数
	 * @param request 请求
	 * @return 页面
	 */
	@RequestMapping("/deleteall")
	@SystemControllerLog(description = "删除用户列表")
	public String deleteall(@ModelAttribute SysUserForm sysUserForm,
			HttpServletRequest request) {
		if(sysUserForm.getSelectIds() != null){
			String[] ids = sysUserForm.getSelectIds().split(Constants.COMMA);
			for(String id: ids){
				userService.delete(Long.parseLong(id), request);
			}
		}
		return String.format(Constants.REDIRECT, "sys/" + ENTITYNAME);
	}

	/**
	 * 打开用户添加页面
	 * @param map 参数
	 * @return 页面
	 */
	@RequestMapping(value="/add", method= RequestMethod.GET)
	@SystemControllerLog(description = "打开用户添加页面")
	public String openAddPage(Model map){
		map.addAttribute(ENTITYNAME, new SysUser());
		return "sys/" + String.format(Constants.ADDPAGE, ENTITYNAME);
	}

	/**
	 * 保存用户添加记录
	 * @param t 实体
	 * @param bindingResult 校验
	 * @param request 请求
	 * @return 页面
	 */
	@RequestMapping(value="/add", method= RequestMethod.POST)
	@SystemControllerLog(description = "保存用户添加记录")
	public String postAddMessage(@Valid @ModelAttribute(ENTITYNAME) SysUser t,
			BindingResult bindingResult, HttpServletRequest request){
		SysUser user = userService.selectByUsername(t.getUsername());
		if(null != user){
			bindingResult.rejectValue("username", "misFormat", "这个用户名称已经存在了！请更改!");
			return "sys/" + String.format(Constants.ADDPAGE, ENTITYNAME);
		}
		if (!bindingResult.hasErrors()) {
			t.setEnable(1);
			userService.save(t, request);
			return String.format(Constants.REDIRECT, "sys/" + ENTITYNAME);
		} else {
			return "sys/" + String.format(Constants.ADDPAGE, ENTITYNAME);
		}
	}

	/**
	 * 打开用户修改页面
	 * @param map 参数
	 * @param request 请求
	 * @return 页面
	 */
	@RequestMapping(value="/edit", method= RequestMethod.GET)
	@SystemControllerLog(description = "打开用户修改页面")
	public String openEditPage(Model map, HttpServletRequest request){
		Long userId = (Long)request.getSession().getAttribute(Constants.SESSIONID);
		map.addAttribute(ENTITYNAME, userService.selectByKey(userId));
		return "sys/" + String.format(Constants.EDITPAGE, ENTITYNAME);
	}

	/**
	 * 更新用户修改记录
	 * @param t 实体
	 * @param bindingResult 校验
	 * @param request 请求
	 * @param file 参数
	 * @return 页面
	 */
	@RequestMapping(value="/edit", method= RequestMethod.POST)
	@SystemControllerLog(description = "更新用户修改记录")
	public String postEditMessage(@Valid @ModelAttribute(ENTITYNAME) SysUser t,
			BindingResult bindingResult, HttpServletRequest request, @RequestParam("image") MultipartFile file){
		String path = FileUtil.addPhoto(file, request);
		SysUser info = userService.selectByKey(t.getId());
		if(!info.getUsername().equals(t.getUsername())){
			SysUser user = userService.selectByUsername(t.getUsername());
			if(null != user){
				bindingResult.rejectValue("username", "misFormat", "这个用户名称已经存在了！请更改!");
				return "sys/" + String.format(Constants.EDITPAGE, ENTITYNAME);
			}
		}
		if (!bindingResult.hasErrors()) {
			t.setHead(path);
			userService.updateNotNull(t, request);
			return "redirect:/index";
		} else {
			return "sys/" + String.format(Constants.EDITPAGE, ENTITYNAME);
		}
	}

	/**
	 * 浏览用户记录
	 * @param map 参数
	 * @param id 主键
	 * @param sysUserForm 条件参数
	 * @return 页面
	 */
	@RequestMapping(value="/view", method= RequestMethod.GET)
	@SystemControllerLog(description = "浏览用户记录")
	public String openViewPage(Model map, @RequestParam Long id,
			@ModelAttribute SysUserForm sysUserForm){
		SysUser user = userService.selectByKey(id);
		if(null != user.getProvince()){
			user.setProvinceName(redisService.get(user.getProvince().toString()).toString());
		}
		if(null != user.getCity()){
			user.setCityName(redisService.get(user.getCity().toString()).toString());
		}
		if(null != user.getRegion()){
			user.setRegionName(redisService.get(user.getRegion().toString()).toString());
		}
		map.addAttribute(ENTITYNAME, user);
		return "sys/" + String.format(Constants.VIEWPAGE, ENTITYNAME);
	}

	/**
	 * 打开分配角色页面
	 * @param map 参数
	 * @param id 主键
	 * @return 页面
	 */
	@RequestMapping(value="/roles", method= RequestMethod.GET)
	@SystemControllerLog(description = "打开分配角色页面")
	public String openRolesPage(Model map, @RequestParam Long id){
		map.addAttribute("userId", id);
		map.addAttribute("roleList", roleService.queryRoleListWithSelected(id));
		return "sys/sysUser/roles";
	}

	/**
	 * 保存用户角色
	 * @param id 主键
	 * @param roleIds 参数
	 * @return 页面
	 */
	@RequestMapping("/saveUserRoles")
	@SystemControllerLog(description = "保存分配角色记录")
	public String saveUserRoles(@RequestParam Long id, @RequestParam("roleId") String roleIds){
		SysUserRole sur = new SysUserRole();
		sur.setUserId(id);
		sur.setRoleIds(roleIds);
		userRoleService.addUserRole(sur);
		return String.format(Constants.REDIRECT, "sys/" + ENTITYNAME);
	}

	/**
	 * 解锁/锁定用户记录
	 * @param id 主键
	 * @param request 请求
	 * @return 页面
	 */
	@RequestMapping("/enable")
	@SystemControllerLog(description = "解锁/锁定用户记录")
	public String getCityList(@RequestParam Long id, HttpServletRequest request){
		SysUser user = userService.selectByKey(id);
		if(user != null){
			if(user.getEnable() == 1){
				user.setEnable(0);
			}else{
				user.setEnable(1);
			}
			userService.updateAll(user, request);
		}
		return String.format(Constants.REDIRECT, "sys/" + ENTITYNAME);
	}
	
}
